//
//  CBCReadViewController.m
//  CBCReader
//
//  Created by Labanotation on 16/5/30.
//  Copyright © 2016年 okwei. All rights reserved.
//

#import "CBCReadViewController.h"
#import "CBCPowerView.h"
#import "CBCReadParser.h"
#import "CBCReadConfig.h"
#import "CBCReaderDef.h"
#import "CommonFuctions.h"
#if __has_include(<Masonry/Masonry.h>)
#import <Masonry/Masonry.h>
#else
#import "Masonry.h"
#endif
//#import "NSObject+Category.h"
@interface CBCReadViewController ()<CBCReadViewControllerDelegate>
@property(nonatomic,strong)CBCPowerView * powerView;
@property(nonatomic,strong)NSTimer   * timer;
@property(nonatomic,strong)UILabel   * timeLabel;
@property(nonatomic,strong)UILabel   * chapterLabel;
@property(nonatomic,strong)UIImageView * backGroundImage;
@property(nonatomic,strong)UILabel   * pageCountLal;
@property (nonatomic,strong)UILabel * tipLabel;
@end

@implementation CBCReadViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.backGroundImage];
    [self.view addSubview:self.readView];
    [self.view addSubview:self.powerView];
    [self.view addSubview:self.timeLabel];
    [self.view addSubview:self.chapterLabel];
    [self.view addSubview:self.pageCountLal];
    [self.view addSubview:self.tipLabel];
    CGFloat  topGaping = CBCiPhoneX?44:10;
    [self.backGroundImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    [self.readView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.left.equalTo(self.view).offset(LeftSpacing);
        make.bottom.equalTo(self.view).offset(-BottomSpacing);
        make.top.equalTo(self.view).offset(TopSpacing);
    }];
    
    [self.powerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(LeftSpacing-5);
        make.top.equalTo(self.readView.mas_bottom).offset(10);
        make.size.mas_equalTo(CGSizeMake(20, 10));
        
    }];
    [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.powerView.mas_right).offset(5);
        make.centerY.equalTo(self.powerView);
        make.width.equalTo(@100);
        make.height.equalTo(@20);
    }];
    
    [self.chapterLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(LeftSpacing-5);
        make.centerX.equalTo(self.view);
        make.height.equalTo(@15);
        make.top.equalTo(self.view).offset(topGaping);
    }];
    [self.pageCountLal mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.powerView);
        make.height.equalTo(self.timeLabel);
        make.right.equalTo(self.readView);
        make.width.equalTo(@100);
    }];
    [self.tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view);
        make.width.equalTo(self.view);
        make.height.equalTo(@40);
    }];
    
    
    [self checkAndMonitorBatteryLevel];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheme:) name:CBCThemeNotification object:nil];
    [self updateChapter];
    [self timerAction];

}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
        [self.timer fire];

}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self.timer invalidate];
}
-(void)setPage:(NSString *)page{
    _page = page;
    self.pageCountLal.text = page;
}
//更新章节
-(void)updateChapter{
    
    self.chapterLabel.text = self.chapterModel.title;
}
//更新主体颜色通知
-(void)changeTheme:(NSNotification *)no
{
    NSString * imageName = no.object;
    [CBCReadConfig shareInstance].themeImageName = imageName;
    UIImage * backImage = [[CommonFuctions cbcReaderImage:imageName] resizableImageWithCapInsets:UIEdgeInsetsMake(20, 20, 20, 20) resizingMode:(UIImageResizingModeStretch)];
    self.backGroundImage.image = backImage;
    
    
}
-(void)setReadType:(readResultType)readType{
    _readType = readType;
    if (readType == readSuccess){
        self.tipLabel.hidden = YES;
    }else{
        self.tipLabel.hidden = NO;
        if (readType==NetworkError) {
            self.tipLabel.text = @"网络连接错误了！😢";
        }else if(readType==readResultLoading){
            self.tipLabel.text = @"努力加载中...";
        }else{
            self.tipLabel.text = @"内容加载失败了！😢";
        }
    }
    
}
-(CBCReadView *)readView
{
    if (!_readView) {
        _readView = [[CBCReadView alloc] initWithFrame:CGRectZero];
        _readView.content = _content;
        _readView.delegate = self;
    }
    return _readView;
}
-(void)viewDidLayoutSubviews{
    
    [super viewDidLayoutSubviews];
    CBCReadConfig *config = [CBCReadConfig shareInstance];
    if ([CommonFuctions isBlankString: _content.content.string]) {
        return;
    }
    _readView.frameRef = [CBCReadParser parserContent:_content config:config bouds:_readView.bounds];
    [self.readView setNeedsDisplay];
}

-(void)readViewEditeding:(CBCReadViewController *)readView{
    if ([self.delegate respondsToSelector:@selector(readViewEditeding:)]) {
        [self.delegate readViewEditeding:self];
    }
}
-(void)setContent:(CBCContentModel *)content{
    _content = content;
}
-(void)readViewEndEdit:(CBCReadViewController *)readView
{
    if ([self.delegate respondsToSelector:@selector(readViewEndEdit:)]) {
        [self.delegate readViewEndEdit:self];
    }
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.timer invalidate];
    self.timer = nil;
}


#pragma mark - 电池状态获取及监控
- (NSNotificationCenter * _Nonnull)extracted {
    return [NSNotificationCenter defaultCenter];
}

-(void)checkAndMonitorBatteryLevel{
    //拿到当前设备
    UIDevice * device = [UIDevice currentDevice];
    device.batteryMonitoringEnabled = true;
    float level = device.batteryLevel;
    UIDeviceBatteryState state = device.batteryState;
    if (state==UIDeviceBatteryStateCharging) {
        self.powerView.charging =@"1";
    }else{
        self.powerView.charging =@"0";
    }
    [self.powerView setPowerPercent:level];
    //2、monitor
    [[self extracted] addObserver:self selector:@selector(didChangeBatteryLevel:) name:@"UIDeviceBatteryLevelDidChangeNotification" object:device];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didChangeBatteryState:) name:@"UIDeviceBatteryStateDidChangeNotification" object:device];
}

-(void)didChangeBatteryState:(NSNotification*)sender{
    UIDevice *myDevice = sender.object;
    UIDeviceBatteryState state = myDevice.batteryState;
    if (state==UIDeviceBatteryStateCharging) {
        self.powerView.charging =@"1";
    }else{
        self.powerView.charging =@"0";
    }
    
}
- (void)didChangeBatteryLevel:(id)sender{
    //电池电量发生改变时调用
    UIDevice *myDevice = [UIDevice currentDevice];
    [myDevice setBatteryMonitoringEnabled:YES];
    float batteryLevel = [myDevice batteryLevel];
    [self.powerView setPowerPercent:batteryLevel];
}

-(CBCPowerView *)powerView{
    if (!_powerView) {
        _powerView = [[CBCPowerView alloc]initWithFrame:CGRectMake(0, 0, 20, 10)];
        _powerView.backgroundColor = [UIColor clearColor];
        _powerView.charging = @"0";
    }return _powerView;
}
-(NSTimer *)timer{
    if (!_timer) {
        // 创建NSTimer对象
        _timer = [NSTimer timerWithTimeInterval:30 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
        // 加入RunLoop中
        [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
        
    }return _timer;
}


//获取时间
-(void)timerAction{
    
    NSString * time = [self getCurrentTime];
    self.timeLabel.text = time;
}
//获取当前时间
-(NSString*)getCurrentTime{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    [formatter setDateFormat:@"HH:mm"];
    
    //现在时间,你可以输出来看下是什么格式
    NSDate *datenow = [NSDate date];
    
    //----------将nsdate按formatter格式转成nsstring
    NSString *nowtimeStr = [formatter stringFromDate:datenow];
    return nowtimeStr;
    
}
-(UILabel *)timeLabel{
    if (!_timeLabel) {
        _timeLabel = [[UILabel alloc]init];
        _timeLabel.font = [UIFont systemFontOfSize:11];
        _timeLabel.textColor = [UIColor darkGrayColor];
    }return _timeLabel;
}
-(UILabel *)chapterLabel{
    if (!_chapterLabel) {
        _chapterLabel= [[UILabel alloc]init];
        _chapterLabel.font = [UIFont systemFontOfSize:12];
        _chapterLabel.textColor = [UIColor darkGrayColor];
        _chapterLabel.textAlignment = NSTextAlignmentLeft;
    }return _chapterLabel;
}
-(UIImageView *)backGroundImage{
    if (!_backGroundImage) {
        _backGroundImage = [[UIImageView alloc]initWithFrame:self.view.bounds];
        _backGroundImage.backgroundColor = [UIColor whiteColor];
        
        UIImage * backImage = [[UIImage imageNamed:[CBCReadConfig shareInstance].themeImageName] resizableImageWithCapInsets:UIEdgeInsetsMake(20, 20, 20, 20) resizingMode:(UIImageResizingModeStretch)];
        _backGroundImage.image = backImage;
    }return _backGroundImage;
}
-(UILabel *)pageCountLal{
    if (!_pageCountLal) {
        _pageCountLal= [[UILabel alloc]init];
        _pageCountLal.font = [UIFont systemFontOfSize:11];
        _pageCountLal.textColor = [UIColor darkGrayColor];
        _pageCountLal.textAlignment = NSTextAlignmentRight;
    }return _pageCountLal;
}
-(UILabel *)tipLabel{
    if (!_tipLabel) {
        _tipLabel = [[UILabel alloc]init];
        _tipLabel.textColor = [UIColor darkTextColor];
        _tipLabel.textAlignment = NSTextAlignmentCenter;
        _tipLabel.font = [UIFont systemFontOfSize:18];
        _tipLabel.hidden = YES;
    }return _tipLabel;
}
@end
